package com.zhq.cxf.intercept;

import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;
import java.util.List;

/**
 * <pre>
 * @class com.zhq.cxf.intercept.AddHeaderIntercept
 * @description 添加soapHeader信息
 * @author zhq
 * @date 2022/6/2 16:40
 * </pre>
 */
@Component
public class AddHeaderIntercept extends AbstractPhaseInterceptor<SoapMessage> {

    @Value("${user-pairing-server.username}")
    private String username;

    @Value("${user-pairing-server.password}")
    private String password;

    public AddHeaderIntercept() {
        super(Phase.PREPARE_SEND);
    }

    @Override
    public void handleMessage(SoapMessage soapMessage) throws Fault {

        Document document = DOMUtils.createDocument();
        Element root = document.createElementNS("http://cxf.zhq.com/auth", "auth");

        Element name = document.createElement("username");
        name.setTextContent(username);

        Element pwd = document.createElement("password");
        pwd.setTextContent(password);

        root.appendChild(name);
        root.appendChild(pwd);

        List<Header> headers = soapMessage.getHeaders();
        headers.add(new SoapHeader(new QName("addHeader"), root));

    }
}
